const query = require('../../dbConfig/index')

const get = async (ctx,next)=>{
	const body = ctx.request.body
	const offset = (body.pageNumber - 1) * Number(body.pageSize);  
	let sql = 'SELECT * FROM classes';  
	let params = [];  
	if(ctx.state.power!=1&&ctx.state.classes){
		let str = ctx.state.classes.split(",").map(num => parseInt(num))
		sql += sql.includes('WHERE')? ' and classes_id IN (?)':' WHERE classes_id IN (?)';  
		params.push(str);
	}
	  sql += ' LIMIT ? OFFSET ?';  
	  params.push(Number(body.pageSize));  
	  params.push(offset);
	const res = await query(sql,params)
	const total = await query(`SELECT COUNT(*) as total FROM classes`)
	if(res.length>0){
		ctx.body={code:200,data:{records:res,total:total[0].total},msg:'成功'}
		next()
	}else{
		ctx.body={code:0,data:null,msg:'暂无班级数据'}
	}
}
const updata = async (ctx,next)=>{
	const body = ctx.request.body
	await query(`UPDATE classes SET classes_name = ? WHERE classes_id='${body.classesId}'`,[body.classesName])
	ctx.body={code:200,data:null,msg:'成功'}
	next()
	
}
const add = async (ctx,next)=>{
	const body = ctx.request.body
	await query(`INSERT INTO classes (classes_name) VALUES (?)`,[body.classesName])
	ctx.body={code:200,data:null,msg:'成功'}
	next()
}
const remove = async (ctx,next)=>{
	const body = ctx.request.body
	await query(`DELETE FROM classes WHERE classes_id=${body.id}`)
	ctx.body={code:200,data:null,msg:'成功'}
	next()
}
module.exports = {
	get,
	add,updata,remove
}